#include "stdafx.h"
#include "UDPReader.h"

UDPReader::UDPReader(SOCKET socket): m_socket(socket)
{

}
UDPReader::UDPReader(const char *addr, int port)
{

}
UDPReader::~UDPReader()
{
	close();
}

int UDPReader::read(char* buf, int len, sockaddr_in* from, int* fromlen)
{
	if(m_socket == INVALID_SOCKET)
		return -1;

	int ret = recvfrom(m_socket, buf, len, 0, (sockaddr*)from, fromlen);
	if(ret == 0 || ret == SOCKET_ERROR)
		return -1;
	else return ret;
}

int UDPReader::read(char* buf, int len, char* ip, int* port)
{
	sockaddr_in from;
	int fromlen = sizeof(from);
	int ret = read(buf, len, &from, &fromlen);
	if(ret != -1)
	{
		strcpy(ip, inet_ntoa(from.sin_addr));
		*port = from.sin_port;
	}
	return ret;
}

void UDPReader::close()
{
	if(m_socket != INVALID_SOCKET)
	{
		closesocket(m_socket);
		m_socket = INVALID_SOCKET;
	}
}